'''
####
Date : 2024-10-17
Notes: 示教器server
Test: 通讯格式
1. 修改代码执行部分代码---解析代码长度(通讯接收缓存)
    client_socket.recv(10240, 0x40),第二个参数 阻塞/与否
2. 增添视觉通讯功能代码
3. KBot通讯功能完善
4. 0.1.0版本--2024.10.29
####

Modify: 
1. kata新库更换--详见self.robot_control类


####
'''

# -*- coding: utf-8 -*-

import serial
import logging
import time
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

robot_logger=logging.getLogger("processModbusRTU")
robot_logger.setLevel(logging.DEBUG)


class rtu_Master():

    def __init__(self, host = None) -> None:
        super().__init__()
        self._master_init()

    def _master_init(self,):
        try:
            self.rtu_server = modbus_rtu.RtuMaster(serial=serial.Serial("/dev/ttyS5", baudrate=9600, bytesize=8, parity='N', stopbits=1, xonxoff=0))
            self.rtu_server.set_timeout(5.0)
            self.rtu_server.set_verbose(True)
        
        except Exception as e:
            robot_logger.error(e,exc_info=True)
    
    def set_DO(self,num,value):
        try:
            start_addr = num + 12
            self.rtu_server.execute(1,cst.WRITE_SINGLE_REGISTER,starting_address=start_addr,output_value=value)
        except Exception as e:
            robot_logger.error(e,exc_info=True)
    
    def set_Motor(self,num,value):
        try:
            start_addr = num + 16
            self.rtu_server.execute(1,cst.WRITE_SINGLE_REGISTER,starting_address=start_addr,output_value=value)
        except Exception as e:
            robot_logger.error(e,exc_info=True)